package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.model.comment.pojos.ApComment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@SuppressWarnings("ALL")
/**
 * @Description :
 * @author     :LD
 */
@Service
public class CommentHotServiceImpl implements CommentHotService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询热点评论
     * @param entryId 文章id
     * @param apComment
     */
    @Async("taskExecutor")//使用自定义的异步线程
    @Override
    public void findHotComment(Long entryId, ApComment apComment) {
        Query query = Query.query(Criteria.where("entryId").is(entryId)
                .and("flag").is(1))
                .with(Sort.by(Sort.Direction.DESC, "likes"));
        List<ApComment> list = mongoTemplate.find(query, ApComment.class);
        //如果找到了热点评论，需要计算点赞数
        if (list!=null && list.size()>0){
            //查询热点评论的最后一条，也就是评论最少的
            ApComment apComment1 = list.get(list.size() - 1);
            //如果当前的评论点赞数大于apComment1的点赞数
            if (apComment1.getLikes()<apComment.getLikes()){
                //将当前数据替换为热点
                apComment.setFlag((short) 1);
                mongoTemplate.save(apComment);
                //热点评论数不能大于5条
                if (list.size()>=5){
                    apComment1.setFlag((short) 0);
                    mongoTemplate.save(apComment1);
                }
            }
        }else {//没有找到，则将当前评论改为热点评论
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);
        }
    }
}
